package me.flyray.bsin.infrastructure.biz.paychannel.joinpay.payway;

import lombok.extern.slf4j.Slf4j;
import me.flyray.bsin.domain.entity.PayChannelConfig;
import me.flyray.bsin.infrastructure.biz.paychannel.PayChannelConfigBiz;
import me.flyray.bsin.infrastructure.biz.paychannel.joinpay.JoinPayPaymentService;
import me.flyray.bsin.infrastructure.biz.paychannel.joinpay.client.JoinPayClient;
import me.flyray.bsin.infrastructure.biz.paychannel.joinpay.domain.request.UniPayReq;
import me.flyray.bsin.infrastructure.biz.paychannel.joinpay.domain.response.UniPayResponse;
import me.flyray.bsin.infrastructure.biz.paychannel.joinpay.util.MapUtils;
import me.flyray.bsin.infrastructure.utils.ApiResBuilder;
import me.flyray.bsin.payment.channel.wxpay.WxLiteOrderRes;
import me.flyray.bsin.payment.channel.wxpay.model.UnifyOrderReq;
import me.flyray.bsin.payment.common.AbstractRes;
import me.flyray.bsin.payment.enums.PayChannelInterfaceEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicBoolean;


@Slf4j
@Component("weixinXcx")
public class WxLite extends JoinPayPaymentService {

    @Autowired
    private PayChannelConfigBiz payChannelConfigBiz;

    @Autowired
    private JoinPayClient joinPayClient;

    @Override
    public AbstractRes pay(UnifyOrderReq request) throws Exception {
        AtomicBoolean isCache = new AtomicBoolean(true);
        PayChannelConfig payChannelConfig = payChannelConfigBiz.queryPayChannelConfig(request.getBizRoleAppId(),
                request.getBizRoleTypeNo(),
                PayChannelInterfaceEnum.JOIN_PAY.getCode(),
                request.getMerchantPayMode(), isCache);
        request.setPayChannelConfigNo(payChannelConfig.getSerialNo());


        if(!isCache.get()){
            log.info("缓存中未查询到参数配置，从数据库中查询，重新写入缓存。。。");
            payChannelConfigBiz.setPayChannelConfigMapper(payChannelConfig);
        }

        // 构造函数响应数据
        WxLiteOrderRes res = ApiResBuilder.buildSuccess(WxLiteOrderRes.class);

        UniPayReq uniPayReq = buildUniPayReq(request);
        // 调起上游接口
        UniPayResponse uniPayResponse = execute(uniPayReq, req -> joinPayClient.unifiedOrder(MapUtils.convertToMap(req)));
        String payInfo = uniPayResponse.getResult();
        res.setPayInfo(payInfo);
        return res;
    }
}
